<template>

  <!--  <div style="">-->
  <!--    <van-nav-bar title="充电中" left-text="返回" left-arrow @click-left="onClickLeft"/>-->
  <!--  </div>-->

  <div style="margin-top: 40px;text-align: center;">
    <div style="margin-left: 20px;">

      <div style="font-weight: bold">
        您的余额
      </div>
      <div style="margin-top: 10px;font-size: 20px;font-weight: bold;color: forestgreen">
        <span>{{ balance }} RMB</span>
      </div>
    </div>

    <div style="margin-left: 20px;margin-top: 40px;">
      <div style="font-weight: bold">
        本次充电总费用
      </div>
      <div style="margin-top: 10px;font-size: 20px;font-weight: bold;color: red">
        <span>{{ chargingMoney }} RMB</span>
      </div>
    </div>

  </div>
  <div class="foot-div">
    <span><van-button round type="success" size="normal" @click="startCharging()">立即支付</van-button></span>
  </div>
  <van-dialog
      v-model:show="show"
      title="余额不足"
      confirmButtonText="去充值"
      @confirm="goCharge()"
  >
  </van-dialog>
  <van-dialog
      v-model:show="show1"
      title="支付成功"
      confirmButtonText="返回个人主页"
      @confirm="goIndex()"
  >
  </van-dialog>

</template>
<script setup>
import {ref} from 'vue';
import {showDialog} from 'vant';
import router from '@/router'
import {StopCharging} from "@/api/station";
import {BalanceDeduct, UserBalance} from "@/api/pay";

const chargingMoney = ref('')
const balance = ref('0.00')
const show = ref(false)
const show1 = ref(false)
const chargingRecordId = ref(null)

init();

function init() {
  StopCharging().then(res => {
    if (res.data.code === 200000) {
      chargingMoney.value = res.data.data.amountStr
      chargingRecordId.value = res.data.data.id
    } else {
      showDialog({message: '结束充电失败'});
    }
  }).catch(() => {
    showDialog({message: '系统繁忙，请稍后再试'});
  })
}

getUserBalance();

function getUserBalance() {
  UserBalance()
      .then(res => {
        if (res.data.code === 200000) {
          balance.value = res.data.data.balance
        } else {
          showDialog({message: '获取余额失败'});
        }
      }).catch(() => {
    showDialog({message: '系统繁忙，请稍后再试'});
  });
}



function startCharging() {
  if (Number(balance.value) < Number(chargingMoney.value)) {
    show.value = true;
    return;
  }
  const balanceDeductReq = ref({
    deductAmount: chargingMoney.value,
    chargingRecordId: chargingRecordId.value
  })
  BalanceDeduct(balanceDeductReq.value).then(res => {
    if (res.data.code === 200000) {
      show1.value = true;
      // showDialog({message: '支付成功'});
      // router.push('/mine/index')
    } else {
      showDialog({message: '支付失败'});
    }
  }).catch(() => {
    showDialog({message: '系统繁忙，请稍后再试'});
  })
}

function goIndex() {
  router.push('/mine/index')
}
function goCharge(){
  router.push('/user/charge/money')
}
</script>
<style>

image {
  border-width: 0px;
  position: absolute;
  left: 0px;
  top: 0px;
}

.foot-div {
  margin-top: 100px;
  text-align: center;
}
</style>